package v1

import (
	dtosign "sweetsunnyflower/app/http/dto/sign"
	"sweetsunnyflower/app/models/sign"
	"sweetsunnyflower/app/queues"
	"sweetsunnyflower/pkg/auth"
	"sweetsunnyflower/pkg/response"

	"github.com/golang-module/carbon/v2"

	"github.com/gin-gonic/gin"
)

type SignsController struct {
	Controller
}

func (ctrl *SignsController) Index(c *gin.Context) {

	userID := auth.CurrentIntUID(c)

	// 获取用户本周签到记录
	signs, err := sign.GetSignsOfWeek(userID)

	if err != nil {
		response.Abort500(c, "获取数据失败，请稍后再试~")
		return
	}

	fortmatSigns := make([]*dtosign.SignResponse, 0)

	// 构造一个7天全空的数据
	for i := 0; i < 7; i++ {
		fortmatSigns = append(fortmatSigns, dtosign.NewSignResponse(&sign.Sign{Week: i}))
	}

	// 遍历签到数据，填充到7天数据中
	for _, sign := range signs {
		fortmatSigns[sign.Week] = dtosign.NewSignResponse(sign)
	}

	// 格式化签到数据
	// for _, sign := range signs {

	// 	fortmatSigns = append(fortmatSigns, dtosign.NewSignResponse(sign))

	// }

	response.Data(c, fortmatSigns)
}

// 用户签到
func (ctrl *SignsController) Store(c *gin.Context) {

	// 判断用户是否签到
	isSign, _, err := sign.IsSignToday(auth.CurrentIntUID(c))

	if err != nil {
		response.Abort500(c, "签到失败，请稍后再试~")
		return
	}

	if isSign {
		response.Abort403(c, "您今天已经签到，明天再来吧~")
		return
	}

	userID := auth.CurrentIntUID(c)

	// 今天是周几,从0开始
	dayOfWeek := carbon.Now().DayOfWeek() - 1

	signModel := sign.Sign{
		UserID: userID,
		Week:   dayOfWeek,
	}

	signModel.Create()

	if signModel.ID > 0 {

		queues.SignEvent(userID, signModel.ID, 10)

		response.Created(c, signModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}
